import { Group } from "three";
import { Line2 } from "three/examples/jsm/lines/Line2";
import { LineGeometry } from "three/examples/jsm/lines/LineGeometry";
import { LineMaterial } from "three/examples/jsm/lines/LineMaterial";
import { CqkjMap } from "../Basic/CqkjMap";
import { MapElement, MapElementOption } from "../Basic/MapElement";
import { setValue } from "../Util/common";
import { PROJECTION } from "../Util/static";

const matLine = new LineMaterial({
  color: 0xC883FF,
  linewidth: 0.002, // in world units with size attenuation, pixels otherwise
  vertexColors: false,
  dashed: true,
  dashScale: 0.0001,
  alphaToCoverage: false,
  depthTest: false,
  depthWrite: false,
});

export interface CivilAirlineOption extends MapElementOption {
  points: number[][]
  height: number
}

export class CivilAirline extends MapElement<CivilAirlineOption>{

  root = new Group()

  get show(): boolean {
    return this.option.show
  }
  set show(val: boolean) {
    setValue(this.option, 'show', val, () => {
      this.root.visible = val
    })
  }

  get line() {
    return this.root.children[0] as Line2
  }

  constructor(map: CqkjMap, option: CivilAirlineOption) {
    super(map, option)
    const { root } = this
    root.visible=option.show
    const z = PROJECTION.altToZ(option.height)
    const positions: number[] = []
    option.points.forEach((e) => {
      positions.push(PROJECTION.lonToX(e[0]), PROJECTION.latToY(e[1]), z)
    })
    const geometry = new LineGeometry();
    geometry.setPositions(positions);
    const line = new Line2(geometry, matLine);
    line.renderOrder=10
    line.computeLineDistances()
    root.add(line)
    map.scene.add(root);
  }

  focus(){
    const { map, line } = this
    map.zoomTo(line.geometry.boundingSphere!.center, 500000)
  }

  onAfterViewChange(): void {
    matLine.dashScale=75/this.map.stage.control.getDistance()
  }

  onDestroy(): void {
    this.map.scene.add(this.root);
    this.line.geometry.dispose()
  }

}